<template>
  <fragment v-if="!item.hidden">
    <!-- 渲染菜单项 -->
    <template v-if="hasOneShowingChild(item.children,item) && (!onlyOneChild.children||onlyOneChild.noShowingChildren)&&!item.alwaysShow">
        <el-menu-item :index="resolvePath(onlyOneChild.menu.url)" @click="abc(item)">
            <i class="el-icon-location"></i>
            <span slot="title">{{ item.name }}</span>
        </el-menu-item>
    </template>

    <!-- 渲染子菜单 -->
    <el-submenu v-else ref="subMenu" :index="resolvePath(item.menu.url)" popper-append-to-body @click="abc(item)">
      <template slot="title">
           <i class="el-icon-location"></i>
            <span slot="title">{{ item.name }}</span>
      </template>
      <sidebar-item
        v-for="child in item.children"
        :key="child.path"
        :is-nest="true"
        :item="child"
        :base-path="resolvePath(child.path)"
        class="nest-menu"
      />
    </el-submenu>
  </fragment>
</template>

<script>
export default {
  name: 'SidebarItem',
  props: {
    // route object
    item: {
      type: Object,
      required: true,
    },
    isNest: {
      type: Boolean,
      default: false,
    },
    basePath: {
      type: String,
      default: '',
    },
  },
  data() {
    // To fix https://github.com/PanJiaChen/vue-admin-template/issues/237
    // TODO: refactor with render function
    this.onlyOneChild = null
    return {}
  },
  methods: {
    abc(item) {
      console.log('istem', item)
      this.$store.commit('aside/routeslist', { path: item.menu.url, name: item.name })
    },
    hasOneShowingChild(children = [], parent) {
      const showingChildren = children.filter(item => {
        if (item.hidden) {
          return false
        } else {
          // Temp set(will be used if only has one showing child)
          this.onlyOneChild = item
          return true
        }
      })

      // When there is only one child router, the child router is displayed by default
      if (showingChildren.length === 1) {
        return true
      }

      // Show parent if there are no child router to display
      if (showingChildren.length === 0) {
        this.onlyOneChild = { ...parent, path: '', noShowingChildren: true }
        return true
      }

      return false
    },
    resolvePath(routePath) {
      return routePath ? this.basePath + routePath : this.basePath
    },

  },
}
</script>
